package com.wwp.tbshop.activity;


import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.wwp.tbshop.R;
import com.wwp.tbshop.model.bean.AddressList;
import com.wwp.tbshop.model.bean.AllAddressBean;
import com.wwp.tbshop.presenter.AddressChangePresenter;
import com.wwp.tbshop.util.Constant;
import com.wwp.tbshop.util.JsonFileReader;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Xiaokun on 2017/6/15.
 */

public class AddOrEditAddressActivity extends BaseActivity {
    private static final String TAG = "AddOrEditAddressActiviy";
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title_type)
    TextView tvTitleType;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.et_person)
    EditText etPerson;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_select_address)
    TextView tvSelectAddress;
    @Bind(R.id.et_address_detail)
    EditText etAddressDetail;
    @Bind(R.id.cb_setting_default)
    CheckBox cbSettingDefault;

    private ArrayList<AllAddressBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private AddressList.AddressListBean mAddressBean;
    private String mProvince;
    private String mCity;
    private String mAddressArea;

    @Override
    public int getLayoutId() {
        return R.layout.activity_addoredit_address;
    }

    @Override
    protected void init() {
        initAllAddressData();
        processIntent();
    }

    private void processIntent() {
        mAddressBean = (AddressList.AddressListBean) getIntent().getSerializableExtra("mAddressBean");
        if (mAddressBean != null) {
            tvTitleType.setText("修改地址");
            etPerson.setText(mAddressBean.getName());
            etPhone.setText(mAddressBean.getPhoneNumber());
            etAddressDetail.setText(mAddressBean.getAddressDetail());
            tvAddress.setText(mAddressBean.getProvince() + " " + mAddressBean.getCity() + " " + mAddressBean.getAddressArea());
        } else {
            tvTitleType.setText("添加新地址");
            cbSettingDefault.setEnabled(false);
        }
    }

    @OnClick({R.id.iv_back, R.id.tv_save, R.id.tv_select_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                saveData();
                break;
            case R.id.tv_select_address:
                showPickerView();
                break;
        }
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvince = options1Items.get(options1).getPickerViewText();
                mCity = options2Items.get(options1).get(options2);
                mAddressArea = options3Items.get(options1).get(options2).get(options3);
                tvAddress.setText(mProvince + mCity + mAddressArea);
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(20)
                .setOutSideCancelable(false)
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initAllAddressData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<AllAddressBean> allAddressBeen = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = allAddressBeen;

        for (int i = 0; i < allAddressBeen.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < allAddressBeen.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = allAddressBeen.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (allAddressBeen.get(i).getCityList().get(c).getArea() == null
                        || allAddressBeen.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < allAddressBeen.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = allAddressBeen.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<AllAddressBean> parseData(String result) {//Gson 解析
        ArrayList<AllAddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AllAddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), AllAddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void saveData() {
        // AddressChangePresenter presenter = new AddressChangePresenter(this);
        String person = etPerson.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String addressDetail = etAddressDetail.getText().toString().trim();
        String id = null;
        if (mAddressBean != null) {
            id = mAddressBean.getId() + "";
        }
        String zipCode = "10086";
        int isDefault = Constant.NO_DEFAULT_ADDRESS;
        if (cbSettingDefault.isChecked()) {
            isDefault = Constant.IS_DEFAULT_ADDRESS;
        }

        if (person == null || phone == null || addressDetail == null) {
            Toast.makeText(this, "信息不全", Toast.LENGTH_SHORT).show();
            return;
        }
        if (person.length() > 7) {
            Toast.makeText(this, "名字太长", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mProvince == null && mAddressBean == null) {
            Toast.makeText(this, "请选择地址", Toast.LENGTH_SHORT).show();
            return;
        } else if (mAddressBean != null) {
            mProvince = mAddressBean.getProvince();
            mCity = mAddressBean.getCity();
            mAddressArea = mAddressBean.getAddressArea();
        }
        Log.e(TAG, "saveData:" + id + person + phone + mProvince + mCity + mAddressArea + addressDetail + zipCode + isDefault);

        //presenter.saveAddress(id, person, phone, mProvince, mCity, mAddressArea, addressDetail, zipCode, isDefault, 182843);
        AddressList.AddressListBean addressBean;
        Intent intent = new Intent();
        if (id != null) {
            addressBean = new AddressList.AddressListBean(mAddressArea, addressDetail, mCity, Integer.parseInt(id), isDefault, person, phone, mProvince, zipCode);
        } else {
            addressBean = new AddressList.AddressListBean(mAddressArea, addressDetail, mCity, -1, isDefault, person, phone, mProvince, zipCode);
        }
        intent.putExtra("addressbean_updata",addressBean);
        setResult(RESULT_OK, intent);

        finish();
    }

}
